package server;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JList;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JLabel;

import server.players.Player;


public class MainGUI extends JFrame {

	private JPanel contentPane;
	private GameServer oGameServer = null;
	private JList list;
	private DefaultListModel listModel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainGUI frame = new MainGUI();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainGUI() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 177, 327);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		oGameServer = new GameServer(this);
		
		JButton btnStartServer = new JButton("Start Server");
		btnStartServer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				oGameServer.startServer();
			}
		});
		btnStartServer.setBounds(10, 11, 137, 23);
		contentPane.add(btnStartServer);
		
		JButton btnStopServer = new JButton("Stop Server");
		btnStopServer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				oGameServer.stopServer();
			}
		});
		btnStopServer.setBounds(10, 45, 137, 23);
		contentPane.add(btnStopServer);
		
		listModel = new DefaultListModel();
		list = new JList(listModel);
		list.setBounds(10, 94, 137, 150);
		contentPane.add(list);
		
		JButton btnKickUser = new JButton("Kick User");
		btnKickUser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//TODO: Add a kick function
				if(list.getSelectedValue() != null) {
				String sValue = (String)list.getSelectedValue();
				int id = Integer.parseInt(sValue.split("-")[1]);
				oGameServer.Kick(id);
				}
				
				
			}
		});
		btnKickUser.setBounds(10, 255, 137, 23);
		contentPane.add(btnKickUser);
		
		JLabel lblUsers = new JLabel("Users");
		lblUsers.setBounds(10, 79, 46, 14);
		contentPane.add(lblUsers);
	}
	
	public void addPlayerToOnlineList(Player p) {
		//TODO Add a way to display the player name and ID
		listModel.addElement(p.getName() + "-" + p.getId());
	}
	public void removePlayerFromOnlineList(Player p) {
		listModel.removeElement(p.getName() + "-" + p.getId());
	}
}
